<template>
    <el-tabs v-model="editableTabsValue" closable type="card" @tab-remove="removeTab" @tab-click="clickTab">
        <el-tab-pane v-for="item in editableTabs"
                     :key="item.name"
                     :label="item.title"
                     :name="item.name"></el-tab-pane>
    </el-tabs>
</template>

<script>
export default {
    name: "Tabs",
    data() {
        return {};
    },
    computed: {
        editableTabs: {
            get() {
                return this.$store.state.menus.editableTabs
            },
            set(val) {
                this.$store.state.menus.editableTabs = val
            }
        },
        editableTabsValue: {
            get() {
                return this.$store.state.menus.editableTabsValue
            },
            set(val) {
                this.$store.state.menus.editableTabsValue = val
            }
        },
    },
    methods: {
        removeTab(tabName) {
            let tabs = this.editableTabs;
            let tabValue = this.editableTabsValue;
            // 如果 关闭的时首页直接返回
            if (tabValue === 'Index') return
            // 如果关闭的是当前页面 则寻找下一个页面做为当前页
            if (tabName === tabValue) {
                tabs.forEach((tab, index) => {
                    if (tab.name === tabValue) {
                        // 找下一个 或者前一个页面
                        let nextTab = tabs[index + 1] || tabs[index - 1];
                        if (nextTab) tabValue = nextTab.name;
                    }
                })
            }
            // 替换 标签名
            this.editableTabsValue = tabValue;
            // 过滤出除了关闭的标签
            this.editableTabs = tabs.filter(tab => tab.name !== tabName)

            this.$router.push({name: tabValue})

        },
        clickTab(tab) {
            this.$router.push({name: tab.name})
        }
    }
}
</script>

<style scoped>
</style>
